package articles_api

import (
	"context"
	"encoding/json"
	"gin_study_blog/common"
	"gin_study_blog/common/http"
	"gin_study_blog/models"
	"gin_study_blog/service/helper"
	"gin_study_blog/utils"
	"github.com/gin-gonic/gin"
	"github.com/olivere/elastic/v7"
)

type CollectListResponse struct {
	models.ArticleModel
	CreatedAt string `json:"created_at"`
}

// ArticleCollectListView 用户收藏列表
func (ArticlesApi) ArticleCollectListView(c *gin.Context) {
	var cr models.PageInfo
	err := c.ShouldBindQuery(&cr)
	if err != nil {
		http.FailWithCode(http.ParamsError, c)
		return
	}

	_claims, _ := c.Get("user")
	claims := _claims.(*utils.UserClaims)

	var articleIDList []interface{}

	list, count, err := helper.CommonList(models.UserCollectsModel{UserID: claims.UserID}, helper.Option{
		PageInfo: cr,
	})

	var collMap = map[string]string{}
	for _, model := range list {
		articleIDList = append(articleIDList, model.ArticleID)
		collMap[model.ArticleID] = model.CreatedAt.Format("2006-01-02 15:04:05")
	}
	boolSearch := elastic.NewTermsQuery("_id", articleIDList...)

	var collList = make([]CollectListResponse, 0)

	// 传入id 列表, 查询es
	result, err := common.EsClient.Search(models.ArticleModel{}.Index()).
		Query(boolSearch).
		Do(context.Background())
	if err != nil {
		common.Log.Error(err.Error())
		http.FailWithMessage(err.Error(), c)
		return
	}

	for _, hit := range result.Hits.Hits {
		var article models.ArticleModel
		err := json.Unmarshal(hit.Source, &article)
		if err != nil {
			common.Log.Error(err)
			http.FailWithMessage(err.Error(), c)
			return
		}
		collList = append(collList, CollectListResponse{
			ArticleModel: article,
			CreatedAt:    collMap[hit.Id],
		})
	}
	http.IsOkWithList(collList, count, c)
}
